<template>
  <view class="product-page">
    <!-- 顶部导航与搜索栏 -->
    <view class="header">
      <view class="search-container">
        <u-icon name="search" size="20" color="#999" class="search-icon"></u-icon>
        <input 
          type="text" 
          placeholder="搜索产品" 
          v-model="searchKeyword"
          class="search-input"
          @input="handleSearchInput"
          @focus="showSearchHistory"
        >
        </input>
      </view>
    </view>

    <!-- 搜索历史弹窗 -->
    <view class="search-history" v-if="showHistory && searchKeyword === ''">
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <text class="clear-history" @click="clearSearchHistory">清除历史</text>
      </view>
      <view class="history-tags">
        <view 
          class="history-tag" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="searchByHistory(item)"
        >
          {{ item }}
        </view>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-scroll">
      <scroll-view scroll-x class="category-container">
        <view 
          class="category-item" 
          :class="{ active: activeCategory === category.id }"
          v-for="(category, index) in categories" 
          :key="index"
          @click="switchCategory(category.id)"
        >
          {{ category.name }}
        </view>
      </scroll-view>
    </view>

    <!-- 产品列表 -->
    <view class="product-list">
      <view class="filter-bar">
        <text class="filter-text">共 {{ filteredProducts.length }} 件产品</text>
        <view class="sort-options">
          <text 
            class="sort-option" 
            :class="{ active: sortType === 'default' }"
            @click="setSortType('default')"
          >默认</text>
          <text 
            class="sort-option" 
            :class="{ active: sortType === 'price-asc' }"
            @click="setSortType('price-asc')"
          >价格 ↓</text>
          <text 
            class="sort-option" 
            :class="{ active: sortType === 'price-desc' }"
            @click="setSortType('price-desc')"
          >价格 ↑</text>
          <text 
            class="sort-option" 
            :class="{ active: sortType === 'heat' }"
            @click="setSortType('heat')"
          >热力值</text>
        </view>
      </view>

      <!-- 产品网格 -->
      <view class="product-grid">
        <view 
          class="product-card" 
          v-for="(product, index) in filteredProducts" 
          :key="index"
          @click="navigateToDetail(product)"
        >
          <view class="product-image">
            <image 
              :src="product.image" 
              mode="aspectFill"
              :alt="product.name"
            ></image>
            <view class="product-tag" v-if="product.tag">{{ product.tag }}</view>
            <!-- 移除列表页的热力值标签 -->
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <!-- 公司名称 -->
            <text class="company-name" v-if="product.companyName">{{ product.companyName }}</text>
            <view class="product-price">
              <text class="current-price">¥{{ product.price.toFixed(2) }}</text>
              <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice.toFixed(2) }}</text>
            </view>
            <view class="product-views">
              <u-icon name="eye" size="16" color="#999"></u-icon>
              <text class="views-count">{{ product.views }}人浏览</text>
            </view>
          </view>
          <!-- 移除列表页的充值按钮 -->
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMoreProducts">
        <view class="loading" v-if="isLoading">
          <u-icon name="spinner" size="24" color="#666" :spin="true"></u-icon>
          <text class="loading-text">加载中...</text>
        </view>
        <view class="load-more-btn" v-else @click="loadMoreProducts">
          <text>加载更多</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      showHistory: false,
      searchHistory: [],
      
      // 分类相关
      categories: [],
      activeCategory: 0,
      
      // 排序相关 - 保留热力值排序
      sortType: 'heat', // 默认按热力值排序 default, price-asc, price-desc, heat
      
      // 产品相关
      products: [],
      filteredProducts: [],
      pageNum: 1,
      pageSize: 10,
      hasMoreProducts: true,
      isLoading: false
    };
  },
  
  onLoad() {
    // 初始化数据
    this.loadSearchHistory();
    this.fetchCategories();
    this.fetchProducts(false);
  },
   // onTabItemTap() {
	  //  this.pageNum = 1
	  //  this.pageSize = 10
	  //  this.hasMoreProducts = true
	  //  this.isLoading = false
   //    // 初始化数据
   //    this.loadSearchHistory();
   //    this.fetchCategories();
   //    this.fetchProducts(false);
   //  },
  
  methods: {
    // 搜索相关方法
    handleSearchInput() {
      if (this.searchKeyword) {
        this.showHistory = false;
        this.filterProducts();
      } else {
        this.showHistory = true;
        this.filterProducts();
      }
    },
    
    showSearchHistory() {
      if (!this.searchKeyword) {
        this.showHistory = true;
      }
    },
    
    searchByHistory(keyword) {
      this.searchKeyword = keyword;
      this.showHistory = false;
      this.addToSearchHistory(keyword);
      this.filterProducts();
    },
    
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory');
      this.searchHistory = history || [];
    },
    
    addToSearchHistory(keyword) {
      // 去重
      const index = this.searchHistory.indexOf(keyword);
      if (index !== -1) {
        this.searchHistory.splice(index, 1);
      }
      // 限制最多10条记录
      if (this.searchHistory.length >= 10) {
        this.searchHistory.pop();
      }
      // 添加到头部
      this.searchHistory.unshift(keyword);
      // 保存到本地存储
      uni.setStorageSync('searchHistory', this.searchHistory);
    },
    
    clearSearchHistory() {
      this.searchHistory = [];
      uni.removeStorageSync('searchHistory');
    },
    
    // 分类相关方法
    switchCategory(categoryId) {
      this.activeCategory = categoryId;
      this.page = 1;
      this.fetchProducts(true);
    },
    
    // 获取分类
    fetchCategories() {
		if(uni.getStorageSync('newsCategorySettings')){
			this.categories = uni.getStorageSync('newsCategorySettings')
		}else{
			this.$request('api/v1/classList').then(res => {
			  if (res.code==200) {
			    this.categories = res.data;
			  }
			}).catch(err => {
			  console.error('获取分类失败', err);
			});
		}
	  
      
    },
    
    // 排序相关方法
    setSortType(type) {
      this.sortType = type;
      this.filterProducts();
    },
    
    // 产品相关方法
    fetchProducts(reset = false) {
      this.isLoading = true;
      
      // 向后台请求数据
      this.$request('api/v1/products','get', {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        categoryId: this.activeCategory,
        keyword: this.searchKeyword,
        sortType: this.sortType // 传递排序类型给后端
      }).then(res => {
        if (res.code==200) {
          if (reset) {
            this.products = res.rows;
			
          } else {
            this.products = [...this.products, ...res.rows];
          }
          
          // 过滤产品
          this.filterProducts();
          
          // 控制加载更多
          this.isLoading = false;
          this.hasMoreProducts = this.pageNum < res.total;
        }
      }).catch(err => {
        console.error('获取产品失败', err);
        this.isLoading = false;
      });
	  this.isLoading = false;
    },
    
    filterProducts() {
      let result = [...this.products];
      
      // 按分类过滤
      if (this.activeCategory !== 0) {
        result = result.filter(product => product.categoryId === this.activeCategory);
      }
      
      // 按搜索关键词过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(product => 
          product.name.toLowerCase().includes(keyword)
        );
      }
      
      // 按排序方式排序
      switch (this.sortType) {
        case 'price-asc':
          result.sort((a, b) => a.price - b.price);
          break;
        case 'price-desc':
          result.sort((a, b) => b.price - a.price);
          break;
        case 'heat':
          // 按热力值降序排序
          result.sort((a, b) => b.heatValue - a.heatValue);
          break;
        default:
          // 默认按ID排序
          result.sort((a, b) => a.id - b.id);
      }
      
      this.filteredProducts = result;
	  this.isLoading = false;
    },
    
    loadMoreProducts() {
      if (this.isLoading || !this.hasMoreProducts) return;
      
      this.page++;
      this.fetchProducts();
	  this.isLoading = false;
    },
    
    navigateToDetail(product) {
		const imagesStr = JSON.stringify(product.images);
      // 跳转到产品详情页
      uni.navigateTo({
        url: `/pages/goods/detail?id=${product.id}&images=${encodeURIComponent(imagesStr)}`
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/* 样式保持不变，移除了热力值相关样式 */
.product-page {
  background-color: #f5f5f7;
  min-height: 100vh;
}

// 顶部搜索栏
.header {
  background-color: #fff;
  padding: 15rpx 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .search-container {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 30rpx;
    padding: 12rpx 20rpx;

    .search-icon {
      margin-right: 10rpx;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      border: none;
      outline: none;
      height: 40rpx;
      line-height: 40rpx;
    }
  }
}

// 搜索历史
.search-history {
  position: absolute;
  top: 90rpx;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 9;
  padding: 20rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .history-title {
      font-size: 28rpx;
      color: #999;
    }

    .clear-history {
      font-size: 26rpx;
      color: #1677FF;
    }
  }

  .history-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;

    .history-tag {
      background-color: #f5f5f5;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      font-size: 26rpx;
      color: #333;
    }
  }
}

// 分类导航
.category-scroll {
  background-color: #fff;
  padding: 10rpx 0;

  .category-container {
    white-space: nowrap;
    padding: 5rpx 20rpx;

    .category-item {
      display: inline-block;
      padding: 10rpx 25rpx;
      font-size: 28rpx;
      color: #666;
      border-radius: 30rpx;
      margin-right: 10rpx;

      &.active {
        background-color: #1677FF;
        color: #fff;
      }
    }
  }
}

// 产品列表
.product-list {
  padding: 20rpx;

  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .filter-text {
      font-size: 26rpx;
      color: #666;
    }

    .sort-options {
      display: flex;

      .sort-option {
        font-size: 26rpx;
        color: #666;
        margin-left: 30rpx;

        &.active {
          color: #1677FF;
          font-weight: 500;
        }
      }
    }
  }

  .product-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20rpx;
  }

  .product-card {
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease;
    position: relative;

    &:active {
      transform: scale(0.98);
    }

    .product-image {
      position: relative;
      height: 300rpx;
      overflow: hidden;

      image {
        width: 100%;
        height: 100%;
        transition: transform 0.5s ease;
      }

      &:hover image {
        transform: scale(1.05);
      }

      .product-tag {
        position: absolute;
        top: 15rpx;
        left: 15rpx;
        background-color: #ff4d4f;
        color: #fff;
        font-size: 24rpx;
        padding: 5rpx 15rpx;
        border-radius: 4rpx;
      }
    }

    .product-info {
      padding: 15rpx;

      .product-name {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 10rpx;
        height: 78rpx; // 确保两行文字高度
      }

      .company-name {
        font-size: 24rpx;
        color: #666;
        line-height: 1.3;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 10rpx;
        
      }

      .product-price {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .current-price {
          font-size: 30rpx;
          color: #ff4d4f;
          font-weight: 500;
        }

        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
          margin-left: 10rpx;
        }
      }

      .product-views {
        display: flex;
        align-items: center;

        .views-count {
          font-size: 24rpx;
          color: #999;
          margin-left: 5rpx;
        }
      }
    }
  }

  // 加载更多
  .load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx 0;

    .loading {
      display: flex;
      align-items: center;

      .loading-text {
        font-size: 26rpx;
        color: #666;
        margin-left: 15rpx;
      }
    }

    .load-more-btn {
      padding: 12rpx 30rpx;
      border: 1px solid #ddd;
      border-radius: 30rpx;
      font-size: 26rpx;
      color: #666;
    }
  }
}
</style>



